//导入express
const express = require("express");
//创建web服务器
const app = express();
const bodyParser = require("body-parser"); //body参数解析
const fs = require("fs");
const { resolve } = require("path");

const formidable = require("express-formidable");
app.use(bodyParser.urlencoded({ extended: false })); //parse application/x-www-form-urlencoded
app.use(bodyParser.json()); //parse application/json
const auth = "fjkaniufbawletnlaiwhoeifja;osfn";
app.post("/login", (req, res) => {
  const { userName, passWord } = req.body;
  const user = {
    userName: "admin",
    passWord: "123456",
  };
  if (user.userName == userName && user.passWord == passWord) {
    res.send({
      code: 200,
      data: {
        msg: true,
        auth,
      },
    });
  } else {
    res.send({
      code: 888,
      data: {
        msg: "登录失败,用户名或密码错误",
      },
    });
  }
});
app.post("/permission", (req, res) => {
  const { auth: auth1 } = req.body;
  if (auth1 == auth) {
    res.send({
      code: 200,
      data: {
        permission: [
          "oms/demo1",
          "oms/demo2",
          "oms/demo",
          "oms/HomePage",


          // "oms/antdv",
          // "oms/antdv1",
          // "oms/svg",
          // "oms/demo3",
          // "oms/brand",
          // "oms/order"
        ],
      },
    });
  } else {
    res.send({
      code: 888,
      data: {
        msg: "获取用户权限失败!",
      },
    });
  }
});
app.use(function (req, res, next) {
  res.set("Access-Control-Allow-Origin", "*");
  res.set("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
  res.set("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
  if (req.method === "OPTIONS") {
    res.end();
  } else {
    next();
  }
});

app.use(express.static(resolve(__dirname, "./public"))).use(express.json());

app.post("/upload", formidable(), function (req, res, next) {
  // console.log(req.files)
  const image = req.files.file;
  const readStream = fs.createReadStream(image.path);
  const writeStream = fs.createWriteStream("./public/" + image.name);
  readStream.pipe(writeStream);
  res.end("http://localhost:9000/" + image.name);
});

app.listen(9000, () => {
  console.log("服务器启动成功:localhost:9000");
});
